<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>{{ $route.query.id ? '编辑题目' : '新增题目' }}</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 题目标题 -->
        <el-form-item label="题目标题" prop="title">
          <el-input
            v-model="form.title"
            type="textarea"
            :rows="3"
            placeholder="请输入题目标题/题干"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <!-- 分类和知识点选择 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类选择" prop="categoryId">
              <el-popover
                placement="bottom-start"
                width="400"
                trigger="click"
                v-model="categoryPopoverVisible"
              >
                <div class="category-selector">
                  <el-input
                    v-model="categoryFilterText"
                    placeholder="输入分类名称搜索"
                    clearable
                    size="small"
                    prefix-icon="el-icon-search"
                  />
                  <el-tree
                    ref="categoryTree"
                    class="filter-tree"
                    :data="categoryTree"
                    :props="categoryProps"
                    :filter-node-method="filterCategoryNode"
                    node-key="id"
                    highlight-current
                    @node-click="handleCategoryNodeClick"
                  />
                </div>
                <el-tag
                  slot="reference"
                  type="info"
                  closable
                  @close="removeSelectedCategory"
                  v-if="selectedCategory"
                >
                  {{ selectedCategory.name }}
                </el-tag>
                <el-button
                  slot="reference"
                  type="text"
                  icon="el-icon-folder-opened"
                  v-else
                >
                  选择分类
                </el-button>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="知识点选择" prop="categoryIds">
              <el-select
                v-model="form.categoryIds"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入知识点名称或编码"
                :remote-method="searchKnowledge"
                :loading="knowledgeLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="item in knowledgeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 难度选择 -->
        <el-form-item label="题目难度" prop="difficult">
          <el-rate
            v-model="form.difficult"
            :max="5"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900','#ff00bb', '#ff002f']"
            show-text
            :texts="['简单', '偏易', '中等', '偏难', '困难']"
          />
        </el-form-item>

        <!-- 题型选择 -->
        <el-form-item label="题型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="请选择题型"
            style="width: 100%"
            @change="handleTypeChange"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 题目内容 -->
        <el-form-item label="题目内容" prop="content">
          <wang-editor
            v-model="form.content"
            @change="handleContentChange"
            ref="contentEditor"
          />
        </el-form-item>

        <!-- 选项区域 -->
        <el-form-item
          label="题目选项"
          v-if="currentType && currentType.hasOption > 0"
          prop="options"
        >
          <div class="option-list">
            <div
              class="option-item"
              v-for="(option, index) in form.options"
              :key="index"
            >
              <el-row :gutter="10">
                <el-col :span="2">
                  <el-checkbox
                    v-model="option.isCorrect"
                    :true-label="1"
                    :false-label="0"
                    v-if="currentType.hasOption === 2"
                  >{{ option.optionCode }}
                  </el-checkbox>
                  <el-radio
                    v-model="correctOption"
                    :label="option.optionCode"
                    v-else
                  >{{ option.optionCode }}
                  </el-radio>
                </el-col>
                <el-col :span="20">
                  <wang-editor
                    v-model="option.content"
                    @change="handleOptionChange(index, $event)"
                    :ref="'optionEditor' + index"
                  />
                </el-col>
                <el-col :span="2" class="option-actions">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click="removeOption(index)"
                  />
                </el-col>
              </el-row>
            </div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addOption"
            >
              添加选项
            </el-button>
          </div>
        </el-form-item>

        <!-- 答案区域 -->
        <el-form-item
          label="题目答案"
          v-if="currentType && currentType.hasAnswer !== 0"
          prop="answers"
        >
          <div class="answer-list">
            <div
              class="answer-item"
              v-for="(answer, index) in form.answers"
              :key="index"
            >
              <el-row :gutter="10">
                <el-col :span="22">
                  <wang-editor
                    v-model="answer.content"
                    @change="handleAnswerChange(index, $event)"
                    :ref="'answerEditor' + index"
                  />
                </el-col>
                <el-col :span="2" class="answer-actions">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    @click="removeAnswer(index)"
                    v-if="form.answers.length > 1"
                  />
                </el-col>
              </el-row>
            </div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="addAnswer"
              v-if="form.answers.length < 5"
            >
              添加答案
            </el-button>
          </div>
        </el-form-item>

        <!-- 附件上传 -->
        <el-form-item
          label="题目附件"
          v-if="currentType && currentType.hasFile > 0"
        >
          <file-upload-plus
            v-model="form.attachmentList"
            :limit="5"
            :accept="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'jpg', 'jpeg', 'png']"
            :max-size="20"
          />
        </el-form-item>

        <!-- 题目解析 -->
        <el-form-item label="题目解析">
          <wang-editor
            v-model="form.analysis"
            @change="handleAnalysisChange"
            ref="analysisEditor"
          />
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 题目预览 -->
    <el-card shadow="never" class="mt-20">
      <div slot="header" class="clearfix">
        <span>题目预览</span>
      </div>
      <div class="preview-content">
        <h3 class="preview-title">{{ form.title || '题目标题' }}</h3>

        <!-- 分类和知识点 -->
        <div class="preview-tags">
          <el-tag v-if="selectedCategory" size="small">{{ selectedCategory.name }}</el-tag>
          <el-tag
            v-for="knowledge in selectedKnowledges"
            :key="knowledge.id"
            size="small"
            type="info"
          >
            {{ knowledge.name }}
          </el-tag>
          <el-tag v-if="form.difficult" size="small" type="warning">
            难度: {{ difficultyText }}
          </el-tag>
        </div>

        <!-- 题目内容 -->
        <div class="preview-section">
          <div class="section-title">题目内容</div>
<!--          <div class="editor-content-view" v-html="form.content || '<p>题目内容</p>'"></div>-->
          <formula-renderer :html="form.content" />
        </div>

        <!-- 选项预览 -->
        <div class="preview-section" v-if="currentType && currentType.hasOption > 0">
          <div class="section-title">选项</div>
          <div class="preview-options">
            <div
              class="option-item"
              v-for="(option, index) in form.options"
              :key="index"
            >
              <div class="option-code">
                {{ option.optionCode }}.
                <span
                  v-if="option.isCorrect === 1 || option.optionCode === correctOption"
                  class="correct-icon"
                >✓</span>
              </div>
<!--              <div-->
<!--                class="option-content"-->
<!--                v-html="option.content || '<p>选项内容</p>'"-->
<!--              ></div>-->
              <formula-renderer class="option-content" :html="option.content" />

            </div>
          </div>
        </div>

        <!-- 答案预览 -->
        <div class="preview-section" v-if="currentType && currentType.hasAnswer > 0">
          <div class="section-title">答案</div>
          <div class="preview-answers">
            <div
              class="answer-item"
              v-for="(answer, index) in form.answers"
              :key="index"
            >
              <div class="answer-index">{{ index + 1 }}.</div>
<!--              <div-->
<!--                class="answer-content"-->
<!--                v-html="answer.content || '<p>答案内容</p>'"-->
<!--              ></div>-->
              <formula-renderer class="answer-content" :html="answer.content" />

            </div>
          </div>
        </div>

        <!-- 解析预览 -->
        <div class="preview-section" v-if="form.analysis">
          <div class="section-title">解析</div>
          <formula-renderer :html="form.analysis" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import WangEditor from '@/components/WangEditor'
import FileUploadPlus from '@/components/FileUploadPlus'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";
import {
  addQuestion,
  getCategoryTree,
  getQuestion,
  listKnowledge,
  listQuestionTypes,
  updateQuestion
} from '@/api/question2/question'

export default {
  name: 'QuestionInput',
  components: {WangEditor, FileUploadPlus, FormulaRenderer},
  dicts: ['bis_question_difficulty'],
  data() {
    return {
      form: {
        id: null,
        title: '',
        typeId: null,
        content: '',
        contentText: '',
        options: [],
        answers: [],
        categoryId: null,
        categoryIds: [],
        tagIds: [],
        attachmentList: [],
        analysis: '',
        analysisText: '',
        remark: '',
        difficult: 3, // 默认中等难度
        status: 1
      },
      rules: {
        title: [{required: true, message: '请输入题目标题', trigger: 'blur'}],
        typeId: [{required: true, message: '请选择题型', trigger: 'change'}],
        content: [{required: true, message: '请输入题目内容', trigger: 'blur'}],
        categoryId: [{required: true, message: '请选择分类', trigger: 'change'}],
        options: [
          {
            type: 'array',
            required: true,
            validator: (rule, value, callback) => {
              if (this.currentType && this.currentType.hasOption > 0 && (!value || value.length < 2)) {
                callback(new Error('至少需要两个选项'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        answers: [
          {
            type: 'array',
            required: true,
            validator: (rule, value, callback) => {
              if (this.currentType && this.currentType.hasAnswer > 0 && (!value || value.length === 0)) {
                callback(new Error('请输入答案'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ]
      },
      typeList: [],
      currentType: null,
      correctOption: '',
      categoryTree: [],
      categoryProps: {
        label: 'name',
        children: 'children'
      },
      categoryFilterText: '',
      categoryPopoverVisible: false,
      selectedCategory: null,
      knowledgeList: [],
      knowledgeLoading: false
    }
  },
  computed: {
    difficultyText() {
      const texts = ['容易', '偏易', '中等', '偏难', '困难']
      return this.form.difficult ? texts[this.form.difficult - 1] : '未设置'
    },
    selectedKnowledges() {
      return this.knowledgeList.filter(k => this.form.categoryIds.includes(k.id))
    }
  },
  watch: {
    categoryFilterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  created() {
    this.loadQuestionTypes()
    this.loadCategoryTree()
    if (this.$route.query.id) {
      this.loadQuestion(this.$route.query.id)
    } else {
      this.initOptions()
      this.initAnswers()
    }
  },
  methods: {
    async loadQuestion(id) {
      try {
        const response = await getQuestion(id);
        this.form = response.data;
        this.currentType = this.typeList.find(t => t.id === this.form.typeId);

        // 设置分类
        if (this.form.categoryId) {
          this.selectedCategory = this.findCategoryInTree(this.categoryTree, this.form.categoryId);
        }

        // 设置知识点
        if (this.form.categoryIds && this.form.categoryIds.length > 0) {
          await this.searchKnowledge('');
          this.form.categoryIds = response.data.categoryIds.split(',').map(String);
        }

        // 确保选项和答案数据存在
        this.form.options = this.form.options || [];
        this.form.answers = this.form.answers || [];

        // 处理单选正确选项
        if (this.currentType?.hasOption === 1) {
          const correctOption = this.form.options.find(opt => opt.isCorrect === 1);
          this.correctOption = correctOption?.optionCode || '';
        }

        // 确保选项编码存在
        this.form.options.forEach((option, index) => {
          option.optionCode = option.optionCode || String.fromCharCode(65 + index);
        });

        // 等待DOM更新完成后设置编辑器内容
        await this.$nextTick();

        // 设置主内容编辑器
        if (this.$refs.contentEditor) {
          this.$refs.contentEditor.setContent(this.form.content);
        }

        // 设置解析编辑器
        if (this.$refs.analysisEditor) {
          this.$refs.analysisEditor.setContent(this.form.analysis);
        }

        // 设置选项编辑器
        this.form.options.forEach((option, index) => {
          const editorRef = this.$refs[`optionEditor${index}`];
          if (editorRef && editorRef[0] && editorRef[0].setContent) {
            editorRef[0].setContent(option.content);
          }
        });

        // 设置答案编辑器 - 这是修复的重点
        this.form.answers.forEach((answer, index) => {
          const editorRef = this.$refs[`answerEditor${index}`];
          if (editorRef && editorRef[0] && editorRef[0].setContent) {
            editorRef[0].setContent(answer.content);
          } else {
            console.warn(`答案编辑器${index}未找到或未初始化`);
          }
        });

      } catch (error) {
        console.error('加载题目失败:', error);
        this.$message.error('加载题目数据失败');
      }
    },

    // safeSetEditorContent(refName, content) {
    //   return new Promise(resolve => {
    //     const checkEditor = () => {
    //       const editorRef = this.$refs[refName];
    //       if (editorRef && editorRef[0] && editorRef[0].setContent) {
    //         editorRef[0].setContent(content);
    //         resolve(true);
    //       } else {
    //         setTimeout(checkEditor, 50);
    //       }
    //     };
    //     checkEditor();
    //   });
    // },

    findCategoryInTree(categories, id) {
      for (const category of categories) {
        if (category.id === id) {
          return category
        }
        if (category.children && category.children.length > 0) {
          const found = this.findCategoryInTree(category.children, id)
          if (found) return found
        }
      }
      return null
    },

    loadQuestionTypes() {
      listQuestionTypes().then(response => {
        this.typeList = response.data
        if (this.$route.query.id && this.form.typeId) {
          this.currentType = this.typeList.find(t => t.id === this.form.typeId)
        }
      })
    },

    loadCategoryTree() {
      getCategoryTree().then(response => {
        this.categoryTree = response.data
        if (this.$route.query.id && this.form.categoryId) {
          this.selectedCategory = this.findCategoryInTree(this.categoryTree, this.form.categoryId)
        }
      })
    },

    initOptions() {
      // 初始化两个默认选项
      this.form.options = [
        {optionCode: 'A', content: '', contentText: '', isCorrect: 0, sort: 1},
        {optionCode: 'B', content: '', contentText: '', isCorrect: 0, sort: 2}
      ]
    },

    initAnswers() {
      // 初始化一个默认答案
      this.form.answers = [
        {content: '', contentText: '', sort: 1}
      ]
    },

    handleTypeChange(typeId) {
      this.currentType = this.typeList.find(t => t.id === typeId)

      // 根据题型调整选项和答案
      if (this.currentType) {
        if (this.currentType.hasOption === 0) {
          this.form.options = []
        } else if (this.form.options.length === 0) {
          this.initOptions()
        }

        if (this.currentType.hasAnswer === 0) {
          this.form.answers = []
        } else if (this.form.answers.length === 0) {
          this.initAnswers()
        }
      }
    },

    addOption() {
      const lastOption = this.form.options[this.form.options.length - 1]
      const nextCode = lastOption ?
        String.fromCharCode(lastOption.optionCode.charCodeAt(0) + 1) : 'A'

      this.form.options.push({
        optionCode: nextCode,
        content: '',
        contentText: '',
        isCorrect: 0,
        sort: this.form.options.length + 1
      })

      this.$nextTick(() => {
        this.$refs[`optionEditor${this.form.options.length - 1}`][0].focus()
      })
    },

    removeOption(index) {
      if (this.form.options.length <= 2) {
        this.$message.warning('至少需要保留两个选项')
        return
      }
      this.form.options.splice(index, 1)

      // 更新选项编码
      this.form.options.forEach((option, i) => {
        option.optionCode = String.fromCharCode(65 + i)
      })

      // 如果是单选题且删除的是正确选项，重置正确选项
      if (this.currentType.hasOption === 1 && this.correctOption === String.fromCharCode(65 + index)) {
        this.correctOption = ''
      }
    },

    addAnswer() {
      this.form.answers.push({
        content: '',
        contentText: '',
        sort: this.form.answers.length + 1
      })

      this.$nextTick(() => {
        this.$refs[`answerEditor${this.form.answers.length - 1}`][0].focus()
      })
    },

    removeAnswer(index) {
      if (this.form.answers.length <= 1) {
        this.$message.warning('至少需要保留一个答案')
        return
      }
      this.form.answers.splice(index, 1)
    },

    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    handleCategoryNodeClick(data) {
      if (data.isKnowledge === 1) {
        this.$message.warning('请选择分类，而不是知识点')
        return
      }
      this.selectedCategory = data
      this.form.categoryId = data.id
      this.categoryPopoverVisible = false
      this.searchKnowledge('')
    },

    removeSelectedCategory() {
      this.selectedCategory = null
      this.form.categoryId = null
      this.form.categoryIds = []
      this.knowledgeList = []
    },

    async searchKnowledge(query) {
      this.knowledgeLoading = true
      const params = {
        name: query,
        parentId: this.selectedCategory ? this.selectedCategory.id : null
      }

      try {
        const response = await listKnowledge(params)
        this.knowledgeList = response.data
      } finally {
        this.knowledgeLoading = false
      }
    },

    handleContentChange(html) {
      this.form.contentText = this.$refs.contentEditor.getText()
    },

    handleOptionChange(index, html) {
      this.form.options[index].contentText = this.$refs[`optionEditor${index}`][0].getText()
    },

    handleAnswerChange(index, html) {
      this.form.answers[index].contentText = this.$refs[`answerEditor${index}`][0].getText()
    },

    handleAnalysisChange(html) {
      this.form.analysisText = this.$refs.analysisEditor.getText()
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 处理单选情况
          if (this.currentType.hasOption === 1 && this.correctOption) {
            this.form.options.forEach(option => {
              option.isCorrect = option.optionCode === this.correctOption ? 1 : 0
            })
          }

          // 确保categoryIds是数组
          if (typeof this.form.categoryIds === 'string') {
            this.form.categoryIds = this.form.categoryIds.split(',').map(Number)
          }

          const request = this.$route.query.id
            ? updateQuestion(this.form)
            : addQuestion(this.form)

          request.then(response => {
            this.$message.success(this.$route.query.id ? '修改成功' : '添加成功')
            this.$router.push('/question2/list')
          })
        } else {
          this.$message.error('请完善题目信息')
          return false
        }
      })
    },

    resetForm() {
      this.$refs.form.resetFields()
      this.selectedCategory = null
      this.form.categoryId = null
      this.form.categoryIds = []
      this.knowledgeList = []
      this.initOptions()
      this.initAnswers()
      this.currentType = null
      this.correctOption = ''

      // 重置富文本编辑器
      this.$refs.contentEditor.setContent('')
      this.$refs.analysisEditor.setContent('')

      // 重置选项和答案编辑器
      if (this.$refs.optionEditor0) {
        this.$refs.optionEditor0[0].setContent('')
        this.$refs.optionEditor1[0].setContent('')
      }
      if (this.$refs.answerEditor0) {
        this.$refs.answerEditor0[0].setContent('')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.preview-content {
  padding: 20px;

  .preview-title {
    margin: 0 0 15px;
    font-size: 18px;
    color: #333;
  }

  .preview-tags {
    margin-bottom: 20px;

    .el-tag {
      margin-right: 10px;
    }
  }

  .preview-section {
    margin-bottom: 25px;

    .section-title {
      font-size: 16px;
      color: #666;
      margin-bottom: 10px;
      padding-bottom: 5px;
      border-bottom: 1px solid #eee;
    }
  }

  .preview-options {
    .option-item {
      margin-bottom: 15px;
      padding: 10px;
      border-radius: 4px;
      background-color: #f9f9f9;

      .option-code {
        font-weight: bold;
        margin-bottom: 5px;

        .correct-icon {
          color: #67c23a;
          margin-left: 5px;
        }
      }
    }
  }

  .preview-answers {
    .answer-item {
      display: flex;
      margin-bottom: 10px;

      .answer-index {
        font-weight: bold;
        margin-right: 10px;
      }
    }
  }
}

.option-list, .answer-list {
  .option-item, .answer-item {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 4px;
    background-color: #f9f9f9;
  }

  .option-actions, .answer-actions {
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.category-selector {
  padding: 10px;

  .filter-tree {
    margin-top: 10px;
    max-height: 300px;
    overflow-y: auto;
  }
}

.mt-20 {
  margin-top: 20px;
}

.editor-content-view {
  ::v-deep img {
    max-width: 100%;
  }
}
</style>
